<template>
  <div class="">
    <div class="app-content px-4 lg:px-6">
      <!--tab-->
      <el-tabs v-model="tabsName" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="已安装" name="0" />
        <el-tab-pane label="已购买" name="1" />
        <el-tab-pane label="本地应用" name="-1" />
        <el-tab-pane label="应用市场" name="2" />
      </el-tabs>
      <!--应用头部-->
      <div class="flex flex-col lg:flex-row lg:justify-between gap-4">
        <el-form :inline="true" :model="searchData" class="flex-1 min-w-0">
          <el-form-item label="" class="mb-2 lg:mb-0">
            <div class="flex flex-wrap gap-1">
              <el-button
                v-for="typeOption in typeOptions"
                :key="typeOption.value"
                :type="searchData.type === typeOption.value ? 'primary' : ''"
                :plain="searchData.type !== typeOption.value"
                class="text-sm px-2 py-1"
                @click="handleTypeChange(typeOption.value)"
              >
                {{ typeOption.label }}
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="应用名称" class="mb-2 lg:mb-0">
            <el-input v-model="searchData['title like']" placeholder="应用名称名称" class="w-full sm:w-auto" />
          </el-form-item>
          <el-form-item class="mb-2 lg:mb-0">
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button type="warning" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
        <div class="work-button flex flex-wrap gap-2 lg:flex-nowrap">
          <el-button type="primary" @click="onCheckUpgrade">检查更新</el-button>
          <!-- <el-button type="warning" @click="help">帮助</el-button> -->
          <!-- <a href="http://s.dkyx.cc" target="_blank">
            <el-button type="primary">应用中心</el-button>
          </a> -->
        </div>
      </div>
      <!--应用列表-->
      <el-table v-loading="loading" :data="dkTableData" class="w-full" stripe height="calc(100vh - 250px)">
        <el-table-column prop="icon" label="应用信息" :min-width="400" :width="600">
          <template #default="{ row }">
            <div class="flex items-center">
              <div class="w-16 h-16 lg:w-20 lg:h-20 rounded-10px mr-2 flex-shrink-0">
                <el-image :src="row.icon" alt="" class="w-16 h-16 lg:w-20 lg:h-20 rounded-10px">
                  <template #error>
                    <img src="@/assets/default/addon.png" alt="" class="w-16 h-16 lg:w-20 lg:h-20" />
                  </template>
                </el-image>
              </div>
              <div class="flex-1 min-w-0">
                <p class="flex flex-wrap items-center gap-1">
                  <span class="text-14px font-bold">{{ row.title }}</span>
                  <span class="text-12px">
                    ({{ row.version }})
                    <el-tag v-if="row.is_update" type="danger" size="small">新版本</el-tag>
                  </span>
                </p>
                <p class="my-1">
                  <el-button v-if="row.is_update" size="small" type="success" icon="Download" @click="onUpgrade(row)">立即更新 </el-button>
                </p>
                <p class="text-12px text-ellipsis overflow-hidden color-gray max-w-400px min-w-200px line-clamp-2">
                  {{ row.description }}
                </p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type_name" label="类型" :min-width="100">
          <template #default="{ row }">
            <dk-platform-type-tag :type="row.type" :type-name="row.type_name" :app-type="row.app_type" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="标识" :min-width="120">
          <template #default="{ row }">
            <el-tag size="small">
              {{ row.name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="tabsName === '0'" label="授权次数" :min-width="180" :width="220">
          <template #default="{ row }">
            <div v-if="row.count_msg.state == -1">
              <el-tag effect="light" type="danger">无权限</el-tag>
            </div>
            <div v-else>
              <div v-if="row.count_msg" class="flex flex-col gap-2 w-full max-w-160px">
                <!-- 方案1：进度条+文字组合（推荐） -->
                <div>
                  <div class="flex justify-between text-xs mb-1">
                    <span>已用 {{ row.count_msg.used_count }} 次</span>
                    <span>剩余 {{ row.count_msg.count - row.count_msg.used_count }} 次</span>
                  </div>
                  <el-progress
                    :percentage="Math.round((row.count_msg.used_count / row.count_msg.count) * 100)"
                    :color="getUsageColor(row.count_msg)"
                    :show-text="false"
                    :stroke-width="15"
                  />
                </div>
              </div>
              <div v-else>
                <el-tag effect="light" type="success">不限次数</el-tag>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="tabsName == '0' || tabsName == '-1'"
          prop="author"
          label="作者"
          :min-width="120"
          :width="220"
        ></el-table-column>
        <el-table-column label="操作" :min-width="120" :width="tabsName === '-1' ? 120 : 180" fixed="right">
          <template #default="{ row }">
            <template v-if="tabsName === '0'">
              <div class="addon-options-btn flex flex-col gap-1">
                <div class="flex flex-wrap gap-1">
                  <el-button size="small" type="primary" icon="Edit" @click="onAddonEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" icon="Delete" @click="onUninstall(row)">卸载</el-button>
                </div>
                <div class="flex flex-wrap gap-1">
                  <el-button v-if="row.has_addon_config" size="small" type="warning" icon="Setting" @click="onAddonConfig(row)">
                    配置
                  </el-button>
                  <template v-if="row.type != 0">
                    <el-button v-if="row.type === 2" size="small" type="primary" icon="User" @click="showDkPlatformAppUserList(row)">
                      用户
                    </el-button>
                    <el-button v-else size="small" type="primary" icon="Platform" @click="showPlatformAddonList(row)">平台</el-button>
                  </template>
                </div>
              </div>
            </template>
            <template v-if="tabsName === '1'">
              <el-button size="small" type="primary" icon="Edit" @click="onAddonDetail(row)">详情</el-button>
              <el-button
                size="small"
                :type="row.is_install ? 'info' : 'danger'"
                :disabled="row.is_install"
                :icon="row.is_install ? 'Check' : 'Delete'"
                @click="row.is_install ? null : router.push({ path: '/addons/install/' + row.name })"
              >
                {{ row.is_install ? '已安装' : '安装' }}
              </el-button>
            </template>
            <template v-if="tabsName === '2'">
              <el-button size="small" type="primary" icon="Edit" @click="onAddonDetail({ addon: row })">详情</el-button>
              <el-button size="small" type="danger" icon="Delete" @click="onBuyAddon(row)">购买</el-button>
            </template>
            <el-button v-if="tabsName === '-1'" type="danger" @click="handleAddonInstall(row.name)">安装</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页-->
      <el-pagination
        class="mt-20px flex justify-center lg:justify-start"
        background
        :page-sizes="[7, 10, 20, 50]"
        :layout="'sizes,total, ->, prev, pager, next, jumper'"
        :total="total"
        :current-page="page"
        :page-size="pageSize"
        @current-change="currentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <dk-form ref="editForm" :key="chooseAddon.id" :form-data="formData" :is-dialog="true" append-to-body @submit="getList()" />
    <el-dialog v-model="dialogVisible" title="平台列表" width="1000px" top="10vh" :z-index="999">
      <dk-platform-addon-list :key="chooseAddon.id" :addon="chooseAddon" />
    </el-dialog>
    <el-dialog v-model="dialogAppUserVisible" title="小程序用户次数" width="1000px" top="10vh" :z-index="999">
      <dk-platform-app-user-list :key="chooseAddon.id" :addon="chooseAddon" />
    </el-dialog>
    <el-dialog v-model="dialogAddonDetailVisible" title="应用详情" width="800px" top="5vh" :z-index="999">
      <dk-addon-detail :addon="chooseAddon.addon" :type="tabsName" />
    </el-dialog>
    <dk-cloud-login ref="cloudLoginRef" />
  </div>
</template>

<script setup>
import { ref, onMounted, defineOptions } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Check } from '@element-plus/icons-vue'
import { downAddon, getUpdateAddon } from '@/api/cloud/cloud'

import {
  addonInstall,
  changeAddonStatus,
  checkUpgrade,
  getAddonForm,
  getAddonsList,
  getAddonConfigForm,
  addonUnInstall,
  addonUpgrade
} from '@/api/addons'
import DkPlatformAddonList from './components/DkPlatformAddonList.vue'
import DkPlatformAppUserList from './components/DkPlatformAppUserList.vue'

defineOptions({
  name: 'AddonsList'
})

const router = useRouter()
const page = ref(1)
const pageSize = ref(7)
const total = ref(0)
const dkTableData = ref([])
const searchData = ref({
  type: '',
  'title like': ''
})

const typeOptions = [
  { label: '全部', value: '' },
  { label: '系统插件', value: '0' },
  { label: '微信公众平台', value: '1' },
  { label: '小程序集', value: '2' },
  { label: '企业微信', value: '3' },
  { label: '抖音H5', value: '4' },
  { label: '独立平台', value: '5' }
]

const dialogAppUserVisible = ref(false)
const dialogVisible = ref(false)
const formData = ref(null)
const chooseAddon = ref({})
const tabsName = ref('0')
const loading = ref(true)
const editForm = ref(null)
const dialogAddonDetailVisible = ref(false)
const cloudLoginRef = ref(null)

onMounted(() => {
  getList(page.value)
})

const help = () => {
  ElMessageBox.alert(
    '当前页面为应用管理，这里可以自定义应用的图标、名称、描述，除了小程序应用，其他的都是显示平台次数，一个平台添加一种应用，小程序可以在一个平台中添加多个相同的应用，所以可以在这里编辑不同用户的可使用次数。',
    '帮助',
    {
      confirmButtonText: '确定'
    }
  )
}

const getUsageColor = (countMsg) => {
  const percentage = countMsg.used_count / countMsg.count
  if (percentage >= 0.9) return '#f56c6c' // 红色预警
  if (percentage >= 0.7) return '#e6a23c' // 黄色警告
  return '#67c23a' // 绿色正常
}

const getUsagePercentage = (countMsg) => {
  const percentage = countMsg.used_count / countMsg.count
  return Math.round((percentage * 100).toFixed(2))
}

const showPlatformAddonList = (row) => {
  chooseAddon.value = row
  dialogVisible.value = true
}

const showDkPlatformAppUserList = (row) => {
  chooseAddon.value = row
  dialogAppUserVisible.value = true
}

const onAddonEdit = (row) => {
  chooseAddon.value = row
  getAddonForm(row.id).then((res) => {
    formData.value = res.data
    editForm.value.show()
  })
}

const onAddonDetail = (row) => {
  chooseAddon.value = row
  dialogAddonDetailVisible.value = true
}

const onBuyAddon = (row) => {
  const buyUrl = `http://s.dkyx.cc/addon/${row.id}`
  window.open(buyUrl, '_blank')
}

// 添加配置功能
const onAddonConfig = (row) => {
  chooseAddon.value = row
  getAddonConfigForm(row.id).then((res) => {
    formData.value = res.data
    editForm.value.show()
  })
}

// 添加卸载功能
const onUninstall = (row) => {
  ElMessageBox.prompt('此操作将永久删除该应用数据,是否继续?', '提示', {
    inputPlaceholder: '请输入：确认卸载',
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(({ value }) => {
      if (value === '确认卸载') {
        addonUnInstall(row.name)
          .then((res) => {
            ElMessageBox.alert(res.msg, '提示', {
              confirmButtonText: '确定',
              callback: () => {
                getList(page.value)
              }
            })
          })
          .catch(() => {})
      } else {
        ElMessage.info('输入的内容不对')
      }
    })
    .catch(() => {})
}

const handleTabClick = (e) => {
  loading.value = true
  tabsName.value = e.paneName
  getList(1)
}

const handleAddonManage = (id) => {
  router.push({ path: '/addons/list' })
}

const handleAddonInstall = (name) => {
  addonInstall(name)
    .then((res) => {
      ElMessageBox.confirm('安装成功', '提示', {
        confirmButtonText: '确定',
        type: 'success'
      })
        .then(() => {})
        .catch(() => {})
    })
    .catch(() => {})
}

const onSearch = () => {
  getList(1)
}

const onReset = () => {
  searchData.value = {}
  getList(1)
}

const handleTypeChange = (value) => {
  searchData.value.type = value
  getList(1)
}

const currentChange = (currentPage) => {
  getList(currentPage)
}

const handleSizeChange = (size) => {
  pageSize.value = size
  getList(1)
}

const onChangeAddonStatus = (id) => {
  changeAddonStatus(id).then((res) => {
    ElMessage.success(res.msg)
  })
}

const getList = (currentPage) => {
  dkTableData.value = []
  page.value = currentPage
  getAddonsList(page.value, pageSize.value, searchData.value, tabsName.value)
    .then((res) => {
      dkTableData.value = res.data
      total.value = parseInt(res.msg)
      loading.value = false
    })
    .catch((res) => {
      loading.value = false
      cloudLoginRef.value.show()
    })
}

const onCheckUpgrade = () => {
  checkUpgrade()
    .then((res) => {
      getList(page.value)
    })
    .catch(() => {})
}

const onAddonUpgrade = (row) => {
  addonUpgrade(row.name)
    .then((res) => {
      ElMessage.success(res.msg)
      getList(page.value)
    })
    .catch((res) => {
      console.log(res)
    })
}

// 添加升级功能
const onUpgrade = (row) => {
  getUpdateAddon(row.name)
    .then((res) => {
      console.log(res)
      ElMessageBox.confirm(res.data.content, '更新内容[' + res.data.name + ']', {
        dangerouslyUseHTMLString: true,
        cancelButtonText: '稍后更新',
        confirmButtonText: '立即更新'
      })
        .then(() => {
          downAddon(row.name)
            .then((res) => {
              ElMessage.success(res.msg)
              onAddonUpgrade(row)
            })
            .catch((res) => {
              console.log(res)
            })
        })
        .catch(() => {})
    })
    .catch((res) => {})
}
</script>

<style lang="scss"></style>
